﻿using AutoMapper;
using B.S.Data.MES.API.Applications.BaseData.Command.BOMCommand;
using B.S.Domain.BasicData.MaterialManagement.BOM;
using B.S.Infratrctrue;
using B.S.Requst;
using MediatR;
using Yitter.IdGenerator;

namespace B.S.Data.MES.API.Applications.BaseData.CommandHandlers.BOMCommandHandlers
{
    public class AddCodeCommandHandler : IRequestHandler<AddCodeCommand, APIRequst<int>>
    {
        private readonly IBaseRepository<BOM> _bomRepository;
        private readonly IMapper _mapper;
        public AddCodeCommandHandler(IBaseRepository<BOM> bomRepository,IMapper mapper)
        {
            _bomRepository = bomRepository;
            _mapper = mapper;

        }
        public async Task<APIRequst<int>> Handle(AddCodeCommand request, CancellationToken cancellationToken)
        {
            APIRequst<int> result = new APIRequst<int>();
            var parentBom = _bomRepository.GetAll().Where(x => x.BomId == request.ParentBomId && !x.isDel).FirstOrDefault();
            if(parentBom==null)
            {
                result.Code = RequstCode.失败;
                result.Msg = RequstCode.失败.ToString()+"父级BOM编号不存在";
                return  await Task.FromResult(result);
            }
            var childbom = _bomRepository.GetAll().Where(x => x.Materialcode == request.Materialcode && !x.isDel).FirstOrDefault();
            if(childbom==null)
            {
                BOM bom =_mapper.Map<BOM>(request);
                bom.BomId = request.BomId;
                bom.Materialcode = request.Materialcode;
                bom.Bname = request.Bname;
                bom.version = request.version;
                bom.ParentId = request.ParentBomId;
                bom.LevelId = parentBom.LevelId + 1;
                bom.isDel = false;
                bom.IsLeaf = true;
                bom.CreateTime = DateTime.Now;
                await _bomRepository.Add(bom);

            }
            else
            {
                childbom.ParentId = request.ParentBomId;
                childbom.LevelId = parentBom.LevelId + 1;
                childbom.UpdateTime=DateTime.Now;
                await _bomRepository.Update(childbom);
            }

            return await Task.FromResult(new APIRequst<int>
            {

                Code = RequstCode.成功,
                Msg = RequstCode.成功.ToString()
            });




        }
    }
}
